import { queryCheckCurrentPIN, queryCheckNewPINIsUsed, querySavePin } from '@/api/setApi'
import { quitLogin } from '@/utils/common'
import { DigestAuth } from '@/utils/encryption/digestAuth'
import { Message } from '@kedacom/react-next'
import { useContext, useEffect, useImperativeHandle, useState } from 'react'
import { alertModal } from '../Modal'
import { PINViewProps, UpdatePINFormDataProps } from './interface'
import { AppContext } from '@/pages/App/context'
import { getErrorCodeMsg } from '@/plugins/axios/errorCode'
const useIndexHook = (props: PINViewProps, ref: React.Ref<unknown> | undefined) => {
	const AppData = useContext(AppContext)
	/**系统信息 */
	const systemInfo = AppData.system
	/**登录的用户的信息 */
	const userInfo = AppData.user
	const INPUT_WIDTH = 300
	const DEFAULT_TIP = '长度为6-8个字符以内的数字'

	const defaultNewConfirmPIN = {
		newPIN: '',
		newPINCheck: false,
		newPINCheckIcon: '',
		newPINCheckText: '',
		newPINTip: '', //'长度为6-8个字符以内的数字'

		confirmPIN: '',
		confirmPINCheck: false,
		confirmPINCheckIcon: '',
		confirmPINCheckText: '',
	}
	/**PIN码组件默认值 */
	const defaultFormData = {
		currentPIN: '',
		currentPINCheck: false, //true 检查结果正确 false检查结果错误
		currentPINCheckIcon: '', //right PIN码一致 errorPIN码不一致
		currentPINTip: '', //提示语
		...defaultNewConfirmPIN,
	}
	/**是否展示当前PIN码，默认展示 */
	const [formData, setFormData] = useState<UpdatePINFormDataProps>({
		...defaultFormData,
	})
	/**
	 * 暴露组件的方法
	 */
	useImperativeHandle(ref, () => ({
		/**检查内容是否改变 */
		checkIsChanged: () => {
			return checkIsChanged()
		},
		/**保存数据 */
		saveData: () => {
			toSave()
		},
		/**获取表单数据 */
		getData: () => {
			return formData
		},
	}))
	useEffect(() => {
		if (userInfo) {
			DigestAuth.username = (userInfo && userInfo.moid) || ''
			// DigestAuth.realm = systemInfo.realmName || 'kedacom'
		}
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [userInfo, systemInfo])
	useEffect(() => {
		props.onChange && props.onChange(formData)
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [formData])
	useEffect(() => {
		if (formData.confirmPIN) {
			//如果确认PIN码有值 要判断是否一致
			checkNewPINConfirmPINSame(formData.newPIN, formData.confirmPIN, 'confirmPIN')
		}
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [formData.newPIN])
	const toSave = () => {
		let result = checkAllPIN()
		if (!result) {
			return false
		}
		try {
			let certCN = localStorage.getItem('certCN')
			if (!certCN) {
				alertModal({ msg: '证书信息已丢失' })
				return
			}
			let msg = ''
			let value = window.JIT_GW_ExtInterface.ChangePinCode(certCN, 2, formData.currentPIN, formData.newPIN)
			if (value === 0) {
				let m = Message.loading('正在修改，请稍候...')
				querySavePin()
					.then(() => {
						m.hide()
						alertModal({
							msg: 'PIN码修改成功，请重新登录。',
							onOk: () => {
								quitLogin()
							},
						})
					})
					.catch(() => {
						m.hide()
					})
			} else {
				if (value === -536870826) {
					msg = '当前pin码错误'
				} else if (value === -536870815) {
					msg = 'ukey不存在'
				} else {
					msg = '修改PIN码失败'
				}
				alertModal({
					msg: msg,
				})
				// if (window.JIT_GW_ExtInterface.GetLastError() !== '0') {
				// 	//-536870826 pin码错误  -536870815 ukey不存在
				// 	if (
				// 		window.JIT_GW_ExtInterface.GetLastError() === 3758096386 ||
				// 		window.JIT_GW_ExtInterface.GetLastError() === 2148532334 ||
				// 		window.JIT_GW_ExtInterface.GetLastError() === 3758096385
				// 	) {
				// 		msg = '用户取消操作'
				// 	} else if (
				// 		window.JIT_GW_ExtInterface.GetLastError() === -536870815 ||
				// 		window.JIT_GW_ExtInterface.GetLastError() === 3758096481
				// 	) {
				// 		msg = '没有找到有效的证书，如果使用的是KEY，请确认已经插入key'
				// 	} else {
				// 		msg = window.JIT_GW_ExtInterface.GetLastErrorMessage()
				// 	}
				// 	alertModal({
				// 		msg: msg,
				// 	})
				// }
			}
		} catch (e) {}
	}
	const checkIsChanged = () => {
		let isChanged = false //默认没有改变
		let hasVal = formData.currentPIN || formData.newPIN || formData.confirmPIN
		if (hasVal) {
			//有改动
			isChanged = true //内容改变了
		}
		return isChanged
	}

	/**校验新PIN码和重置PIN码输入 */
	const checkAllPIN = () => {
		if (!formData.currentPINCheck) {
			alertModal({
				msg: 'PIN码不一致，请重新输入',
			})
			return false
		}
		if (!formData.newPINCheck) {
			if (formData.newPIN) {
				alertModal({
					msg: '新PIN码不能为空，请输入新PIN码。',
				})
				return false
			} else {
				alertModal({
					msg: '新PIN码不能为空，请输入新PIN码。',
				})
				return false
			}
		}
		if (!formData.confirmPINCheck) {
			if (formData.confirmPIN !== formData.newPIN) {
				alertModal({
					msg: '两次输入PIN码不一致，请重新输入。',
				})
				return false
			}
		}
		return true
	}
	/**
	 * 输入框改变时
	 * @param v PIN码的值
	 * @param name PIN码的键名
	 */
	const onInputChange = (v: string, name: string) => {
		if (name === 'currentPIN') {
			currentPINChange(v, name)
		} else if (name === 'newPIN') {
			newPINChange(v, name)
		} else {
			//确认PIN码改变时
			confirmPINChange(v, name)
		}
	}

	/**
	 * 输入框聚焦时
	 * @param v PIN码的值
	 * @param name PIN码的键名
	 */
	const onInputFocus = (string: any, name: string) => {
		if (name === 'newPIN') {
			//新PIN码
			const showCurrentPIN = props.isShowCurrentPIN === false ? false : true
			const tip = showCurrentPIN ? (formData.currentPINCheck ? DEFAULT_TIP : '') : DEFAULT_TIP
			setFormData({
				...formData,
				newPINTip: tip,
			})
		}
		//聚焦到确认PIN码时 校验新PIN码的输入
		// if (name === 'confirmPIN') {
		// 	if (formData.currentPINCheck) {
		// 		if (formData.newPIN === '') {
		// 			setFormData({
		// 				...formData,
		// 				newPINCheck: false,
		// 				newPINCheckIcon: 'error',
		// 				newPINCheckText: 'PIN码不得为空',
		// 			})
		// 		}
		// 	}
		// }
	}

	/**
	 * 当前PIN码改变时，隐藏后面的PIN码是否一致的提示，没有值时，清空后面的新PIN码和确认PIN码
	 * @param v 当前PIN码的值
	 * @param name 当前PIN码的键名
	 */
	const currentPINChange = (v: string, name: string) => {
		if (!v) {
			resetAllPIN()
			return false
		}
		setFormData({
			...formData,
			currentPINCheckIcon: '',
			[name]: v,
			currentPINCheck: v ? formData.currentPINCheck : false, //校验在无值的时候检验
		})
	}

	/**
	 * 新PIN码改变时
	 * @param v 新PIN码的值
	 * @param name 新PIN码的键名
	 */
	const newPINChange = (v: string, name: string) => {
		let newPINCheckIcon = 'error' ////根据检查结果做的图标提示
		let newPINCheck = false //默认输入的新PIN码不符合规则
		let newPINCheckText = '' //根据检查结果做的文字提示
		//如果清空了新PIN码，要更新新PIN码和确认PIN码的状态，自动清空确认PIN码的值
		if (!v) {
			resetNewConfirmPIN()
			return false
		}
		//如果有值，检验判断
		if (6 > v.length && v.length > 8) {
			newPINCheckText = '长度为6-8个字符'
		} else {
			//判断是否满足
			let reg = /^[0-9\\-]{6,8}$/
			if (reg.test(v)) {
				//符合规则
				newPINCheckIcon = 'strong'
				newPINCheckText = '格式正确'
				newPINCheck = true
				// break
			} else {
				//三种强度规则都不符合
				newPINCheckIcon = 'error'
				newPINCheckText = 'PIN码不符合要求'
				newPINCheck = false
			}
		}
		/**输入的新PIN码是否和当前PIN码一样 */
		let isSameToCurrentPIN = formData.currentPIN && v && formData.currentPIN === v
		if (isSameToCurrentPIN) {
			newPINCheckIcon = 'error'
			newPINCheckText = '新旧PIN码不得相同'
			newPINCheck = false
		}
		setFormData({
			...formData,
			newPINCheckIcon,
			newPINCheckText,
			newPINCheck,
			[name]: v,
		})
	}
	/**
	 * 确认PIN码改变时
	 * @param v 输入的值
	 * @param name 键名
	 */
	const confirmPINChange = (v: string, name: string) => {
		checkNewPINConfirmPINSame(formData.newPIN, v, name)
	}
	/**
	 * 判断新PIN码和确认PIN码是否一致
	 * @param newPIN 新PIN码
	 * @param confirmPIN 确认PIN码
	 * @param name 键名
	 */
	const checkNewPINConfirmPINSame = (newPIN: string, confirmPIN: string, name: string) => {
		let confirmPINCheckIcon = 'error',
			confirmPINCheckText = 'PIN码不一致',
			confirmPINCheck = false
		if (!newPIN && !confirmPIN) {
			confirmPINCheckIcon = ''
			confirmPINCheckText = ''
			confirmPINCheck = false
		} else {
			if (newPIN === confirmPIN) {
				confirmPINCheckIcon = 'right'
				confirmPINCheckText = 'PIN码一致'
				confirmPINCheck = true
			}
		}
		setFormData({
			...formData,
			confirmPINCheckIcon,
			confirmPINCheckText,
			confirmPINCheck,
			[name]: confirmPIN,
		})
	}
	/**
	 * 鼠标在当前PIN码失去焦点时 判断PIN码输入是否一致
	 * 如果不一致 新PIN码和确认PIN码禁止输入&&清空已输入的内容
	 * @param v 输入的值
	 * @param name 键名字
	 */
	const onInputBlur = (v: string, name: string) => {
		if (name === 'currentPIN') {
			onCurrentPINBlur(v)
		}
		if (name === 'newPIN') {
			onNewPINBlur(v)
		}
	}
	/**
	 * 当前PIN码失去焦点时 判断输入的PIN码是否是当前用户的PIN码
	 * @param v 输入值
	 * @returns
	 */
	const onCurrentPINBlur = (v: string) => {
		if (!v) {
			//当前PIN码有值时接口校验输入是否正确
			return false
		}
		if (v) {
			let dataJson = {
				moid: userInfo ? userInfo.moid : '',
			}
			let data = DigestAuth.makePassword(v, v)
			dataJson = {
				...dataJson,
				...data,
			}
			setFormData({
				...formData,
				currentPINCheck: true,
				currentPINCheckIcon: 'right',
			})
			// queryCheckCurrentPIN(dataJson)
			// 	.then(() => {
			// 		setFormData({
			// 			...formData,
			// 			currentPINCheck: true,
			// 			currentPINCheckIcon: 'right', //失去焦点时如果没有value，不展示PIN码是否一致的提示
			// 		})
			// 	})
			// 	.catch(() => {
			// 		setFormData({
			// 			...formData,
			// 			currentPINCheckIcon: 'error',
			// 			...defaultNewConfirmPIN,
			// 		})
			// 	})
		}
	}
	/**检查新PIN码是否是历史PIN码 */
	const onNewPINBlur = (v: string) => {
		if (formData.newPINCheck) {
			// defaultCheckUsedOnNewPINBlur(v)
		}
	}
	/**
	 * 重置新PIN码和确认PIN码
	 */
	const resetNewConfirmPIN = () => {
		setFormData({
			...formData,
			...defaultNewConfirmPIN,
		})
	}
	/**
	 * 重置确认PIN码
	 */
	const resetAllPIN = () => {
		setFormData({
			...defaultFormData,
		})
	}
	return {
		INPUT_WIDTH,
		formData,
		onInputChange,
		onInputBlur,
		onInputFocus,
	}
}
export default useIndexHook
